package com.rupertjones.globalcron.web.init;

import com.rupertjones.globalcron.domain.audit.AuditLoggingPostPersistenceEventListener;
import com.rupertjones.globalcron.domain.dao.SessionContextProvider;
import com.rupertjones.globalcron.domain.dao.PostPersistenceEventListener;
import org.apache.log4j.Logger;
import org.hibernate.event.PostDeleteEventListener;
import org.hibernate.event.PostInsertEventListener;
import org.hibernate.event.PostUpdateEventListener;
import org.hibernate.impl.SessionFactoryImpl;
import org.joda.time.DateTime;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.InputStream;
import java.util.Properties;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
public class InitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger LOG = Logger.getLogger(InitServlet.class);

    public void init() throws ServletException {
        super.init();
        String version = getVersion();
        getServletContext().setAttribute("version", version);
        getServletContext().setAttribute("started", new DateTime().toString("dd/MM/yyyy hh:mm:ss (ZZZ)"));

        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

        PostPersistenceEventListener selectingListener = (PostPersistenceEventListener) context.getBean("selectingPostPersistenceEventListener");
        SessionFactoryImpl sessionFactoryBean = (SessionFactoryImpl) context.getBean("sessionFactory");
        sessionFactoryBean.getEventListeners().setPostDeleteEventListeners(new PostDeleteEventListener[]{selectingListener});
        sessionFactoryBean.getEventListeners().setPostUpdateEventListeners(new PostUpdateEventListener[]{selectingListener});
        sessionFactoryBean.getEventListeners().setPostInsertEventListeners(new PostInsertEventListener[]{selectingListener});

        AuditLoggingPostPersistenceEventListener listener = (AuditLoggingPostPersistenceEventListener) context.getBean("auditLoggingPostPersistenceEventListener");
        SessionContextProvider provider = (SessionContextProvider) context.getBean("webSessionPersistenceContextProvider");
        listener.setSessionContextProvider(provider);
    }

    private String getVersion() {
        try {
            InputStream inputStream = getServletContext().getResourceAsStream("/META-INF/maven/com.rupertjones.global-cron/global-cron-web/pom.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            return (String) properties.get("version");
        } catch (Throwable th) {
            LOG.warn("Could not read manifest file.");
            return "DEVELOPMENT BUILD";
        }
    }
}
